package PageUtils

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Slice"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Sort"
)

func GetMapPageList(entityList []map[string]interface{}, pageNum, pageSize int) map[string]interface{} {
	data := make(map[string]interface{})
	data["total"] = len(entityList)

	resultList := make([]map[string]interface{}, 0)

	pageStartId := pageSize * (pageNum - 1)
	pageEndId := pageSize * pageNum
	index := 0

	for _, entity := range entityList {
		if index < pageStartId {
			index++
			continue
		}
		if index >= pageEndId {
			break
		}

		resultList = append(resultList, entity)
		index++
	}

	data["list"] = resultList

	return data
}

func GetPageList[T any](list []T, pageNum, pageSize int) []T {
	resultList := make([]T, 0)

	pageStartId := pageSize * (pageNum - 1)
	pageEndId := pageSize * pageNum
	index := 0

	for _, entity := range list {
		if index < pageStartId {
			index++
			continue
		}
		if index >= pageEndId {
			break
		}

		resultList = append(resultList, entity)
		index++
	}

	return resultList
}

// SortAndMapPageList 根据value先排序再分页
// 参数说明：
// data map[string]interface{}格式的哈希表数据
// valueType data的value的数据类型的范例，用于进行数组转换的时候，告知数组的具体类型
// pageNum, pageSize 分页参数
// orderBy 排序函数
func SortAndMapPageList[V any](data map[string]interface{}, valueType V, pageNum, pageSize int, orderBy Sort.OrderBy) []V {
	keys := Map.GetKeys(data)
	Sort.Sort(keys, orderBy)

	keys = GetPageList(keys, pageNum, pageSize)

	result := make([]interface{}, 0)
	for _, key := range keys {
		value := data[key].(V)

		result = append(result, value)
	}

	return Slice.ToList(result, valueType)
}
